package handler

import (
	"context"
	"examination-management/srv/cmd/config"
	"examination-management/srv/cmd/model"
	pb "examination-management/srv/proto"
)

type Server struct {
	pb.UnimplementedExaminationServer
}

func (s *Server) CreateTestManagement(_ context.Context, in *pb.CreateTestManagementReq) (*pb.CreateTestManagementResp, error) {
	var m model.TestManagement
	config.DB.Debug().Where("test_questions = ?", in.TestQuestions).Limit(1).Find(&m)
	if m.Id != 0 {
		return &pb.CreateTestManagementResp{
			Message: "试题已存在",
			Code:    10001,
		}, nil
	}
	management := model.TestManagement{
		TestQuestionType:     in.TestQuestionType,
		Difficulty:           in.Difficulty,
		ProfessionalScopeOne: in.ProfessionalScopeOne,
		ProfessionalScopeTwo: in.ProfessionalScopeTwo,
		Author:               in.Author,
		TestQuestions:        in.TestQuestions,
	}
	err := config.DB.Debug().Create(&management).Error
	if err != nil {
		return &pb.CreateTestManagementResp{
			Message: "添加失败",
			Code:    10002,
		}, nil
	}
	return &pb.CreateTestManagementResp{
		Message: "添加成功",
		Code:    200,
	}, nil
}
func (s *Server) UpdateTestManagement(_ context.Context, in *pb.UpdateTestManagementReq) (*pb.UpdateTestManagementResp, error) {
	var m model.TestManagement
	config.DB.Debug().Where("id = ?", in.TMId).Limit(1).Find(&m)
	if m.Id == 0 {
		return &pb.UpdateTestManagementResp{
			Message: "试题不存在",
			Code:    10001,
		}, nil
	}
	management := model.TestManagement{
		Id:                   in.TMId,
		TestQuestionType:     in.TestQuestionType,
		Difficulty:           in.Difficulty,
		ProfessionalScopeOne: in.ProfessionalScopeOne,
		ProfessionalScopeTwo: in.ProfessionalScopeTwo,
		Author:               in.Author,
		TestQuestions:        in.TestQuestions,
	}
	err := config.DB.Debug().Updates(&management).Error
	if err != nil {
		return &pb.UpdateTestManagementResp{
			Message: "更新失败",
			Code:    10002,
		}, nil
	}
	return &pb.UpdateTestManagementResp{
		Message: "更新成功",
		Code:    200,
	}, nil
}
